package com.myblog.controller;

import com.myblog.constant.CodeType;
import com.myblog.mapper.CommentMapper;
import com.myblog.model.User;
import com.myblog.service.CommentService;
import com.myblog.service.LeaveService;
import com.myblog.service.UserService;
import com.myblog.utils.DataMap;
import com.myblog.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Slf4j
@RestController
public class MsgReadController {

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LeaveService leaveService;

    /**
     * 个人页面全部已读留言或者评论
     * @param msgType
     * @param request
     * @return
     */
    @GetMapping("/readAllMsg")
    public String readAllMsg(@RequestParam(value = "msgType")Integer msgType, HttpServletRequest request){
        try {
            Principal userPrincipal = request.getUserPrincipal();
            if(userPrincipal == null){
                return JsonResult.fail(CodeType.USER_NOT_LOGIN).toJSON();
            }
            User user = userService.searchUserByName(userPrincipal.getName());
            Integer respondentId = user.getId();
            if (msgType == 1){
                DataMap data = commentService.setAllCommentIsRead(respondentId);
                return JsonResult.build(data).toJSON();
            }
            else if(msgType == 2){
                DataMap data = leaveService.setAllLeaveIsRead(respondentId);
                return JsonResult.build(data).toJSON();
            }
            else {
                return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
            }
        }catch (Exception e){
            log.error("MsgReadController readAllMsg Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }
}
